#!/usr/bin/python

import urllib,urllib2,re,xbmcplugin,xbmcgui
import os,datetime,base64,httplib
from BeautifulSoup import BeautifulStoneSoup
import pyamf
from pyamf import remoting, amf3, util
pluginhandle = int(sys.argv[1])

################################ Common
txheaders = {
    'Referer': 'http://www.mylifetime.com',
    'X-Forwarded-For': '12.13.14.15',
    'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US;rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)',
}

def getURL( url ):
    try:
        print 'Lifetime --> getURL :: url = '+url
	txdata = None
        global txheaders  
        req = urllib2.Request(url, txdata, txheaders)
        response = urllib2.urlopen(req)
	link=response.read()
	response.close()
    except urllib2.URLError, e:
        error = 'Error code: '+ str(e.code)
        xbmcgui.Dialog().ok(error,error)
        print 'Error code: ', e.code
        return False
    else:
        return link


def addLink(name,url,mode,iconimage='',plot='',season=0,episode=0,showname='',duration='',fanart=''):
   u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+'&thumbnail='+urllib.quote_plus(iconimage)
   ok=True
   liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
   liz.setInfo( type="Video", infoLabels={ "Title": name,
                                           "Plot":plot,
                                           "Season":season,
                                           "Episode":episode,
                                           "Duration":duration,
                                           "TVShowTitle":showname})
   if fanart!='':
      liz.setProperty('fanart_image', fanart)
   liz.setProperty('IsPlayable', 'true')
   ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz)
   return ok

def addDir(name,url,mode,iconimage='',plot='',fanart=''):
   u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+'&thumbnail='+urllib.quote_plus(iconimage)
   ok=True
   liz=xbmcgui.ListItem(name, iconImage='DefaultFolder.png', thumbnailImage=iconimage)
   liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot":plot})
   if fanart!='':
      liz.setProperty('fanart_image', fanart);
   ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz,isFolder=True)
   return ok

################################ Root listing
def ROOT():
   EPISODE()

def EPISODE():
   xbmcplugin.setContent(pluginhandle, 'episodes')
   xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_NONE)

   episode_list = getEpisodeList('http://www.mylifetime.com/d6/views/ajax?js=1&page=0&view_name=video_watch_full_episodes_assoc&view_display_id=block_1&view_args=&view_path=watch-full-episodes-online&view_base_path=null&view_dom_id=video-watch-full-episodes-assoc-block-1&pager_element=0')
   for episode in episode_list:
      name = episode[0]
      thumbnail = episode[1]
      duration = episode[2]
      plot = episode[3]
      sid = episode[4]
      seasonNum = 0
      episodeNum = 0
      mode = 5 #PLAYEPISODE
      fanart = 'special://home/addons/plugin.video.lifetime/fanart.jpg'
      addLink(name,sid,mode,thumbnail,plot,seasonNum,episodeNum,name,duration,fanart)
   xbmcplugin.endOfDirectory(pluginhandle)

def PLAYEPISODE(url):
   data = getURL(url)

   default_video_id = re.compile('"defaultVideoID":"(\d+)"').findall(data)[0]
   print "VideoID:%s" % default_video_id

   pdk_flash_url = re.compile('"platform_id":"'+default_video_id+'",.+?"pdk_flash_url":"(.+?)[\?|"]').findall(data)[0]
   pdk_flash_url = pdk_flash_url.replace('\\', '')

   print "PDK:%s" % pdk_flash_url

   sig_url = re.compile('/s/(.+)').findall(pdk_flash_url)[0]
   sig = getURL('http://servicesaetn-a.akamaihd.net/jservice/video/components/get-signed-signature?url='+sig_url)

   pdk_flash_url += "?mbr=true&sig="+sig+"&format=SMIL&Tracking=true&Embedded=true"

   data = getURL(pdk_flash_url)

   playpath = re.compile('<video src="(.+?)"').findall(data)[0]

   item = xbmcgui.ListItem(path=playpath)
   return xbmcplugin.setResolvedUrl(pluginhandle, True, item)


def getEpisodeList(url):
   episode_list = []

   episode_list.extend(getEpisodeFromJs(url))

   current_page = 1

   link = getURL('http://www.mylifetime.com/watch-full-episodes-online')
   pages=re.compile('<div class="video-rollover-container-navigation-input">1</div> of (\d+)</li>').findall(link)
   while(current_page<int(pages[0]) and current_page<5):
   	episode_list.extend(getEpisodeFromJs('http://www.mylifetime.com/d6/views/ajax?js=1&page='+str(current_page)+'&view_name=video_watch_full_episodes_assoc&view_display_id=block_1&view_args=&view_path=watch-full-episodes-online&view_base_path=null&view_dom_id=video-watch-full-episodes-assoc-block-1&pager_element=0'))
   	current_page += 1

   return episode_list


def episodeHTMLParser(link):
   print link
   episode_list = []
   ep_ids_urls = re.compile('<div class="video-image-wrapper video-.+?">.*?\n.+?<a id="video-image-link-(\d+)".+?title="(.+?)".+?href=\"(http://www.mylifetime.com/shows/.+?)\"').findall(link)
   print 'EpIds:'+str(len(ep_ids_urls))
   ep_images = re.compile('<div class="video-rollover-container-middle-player">.*?\n.*?<img src="(.+?)"').findall(link)
   print 'Images:'+str(len(ep_images))
   ep_titles = re.compile('<div class="video-rollover-container-middle-player-text">.*?\n.*?<b>(.+?)</div>').findall(link)
   print 'EpTitles:'+str(len(ep_titles))
   premium = re.compile('<div class="video-play-symbol is-premium" id="video-play-symbol video-play-symbol-(\d+)"></div>').findall(link)
   #duration info is incomplete
   #ep_durations = re.compile('<div class="video-rollover-container-player-date-text">.*?\n.*?(\d+)min').findall(link)
   #print 'EpDurations:'+str(len(ep_durations))

   for i in range(len(ep_ids_urls)):
      if(ep_ids_urls[i][0] not in premium):
      	print "EpURL:%s" % ep_ids_urls[i][2]
      	episode_list.append((str(BeautifulStoneSoup(ep_titles[i], convertEntities=BeautifulStoneSoup.HTML_ENTITIES)), 
                           ep_images[i], 
			   "0",
			   str(BeautifulStoneSoup(remove_html_tags(ep_ids_urls[i][1]), convertEntities=BeautifulStoneSoup.HTML_ENTITIES)),
			   ep_ids_urls[i][2]))
   
   return episode_list

def getEpisodeFromJs(url):
   print 'Lifetime --> getEpisodeFromJs :: url = '+url
   link = getURL(url)
   link = link.replace(r'\r\n', '\n')
   link = link.replace(r'\t', '\t')
   link = link.replace(r'\x3c', '<')
   link = link.replace(r'\x3e', '>')
   link = link.replace(r'\x26', '&')
   link = link.replace(r'\/', '/')
   link = link.replace(r'\"', '"')
   episode_list = episodeHTMLParser(link)
   
   return episode_list


def remove_html_tags(data):
   p = re.compile(r'<.*?>')
   return p.sub('', data)

def get_params():
   param=[]
   paramstring=sys.argv[2]
   print paramstring
   if len(paramstring)>=2:
      params=sys.argv[2]
      cleanedparams=params.replace('?','')
      if (params[len(params)-1]=='/'):
         params=params[0:len(params)-2]
      pairsofparams=cleanedparams.split('&')
      param={}
      for i in range(len(pairsofparams)):
         splitparams={}
         splitparams=pairsofparams[i].split('=')
         if (len(splitparams))==2:
            param[splitparams[0]]=splitparams[1]
                                
   return param


params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
try:
        thumbnail=urllib.unquote_plus(params["thumbnail"])
except:
        thumbnail=''

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Thumb:"+str(thumbnail)

if mode==None or url==None or len(url)<1:
   ROOT()
elif mode==1:
   pass
elif mode==2:
   pass
elif mode==3:
   EPISODE(name,url)
elif mode==4:
   pass
elif mode==5:
   PLAYEPISODE(url)

	       
